import { ElMessage } from 'element-plus';
import { deepCopy } from '/@/utils';
import { useArticleApi } from '/@/api/article';

const { getArticleCateList, addArticleCate, editArticleCate } = useArticleApi();

export const rules = {
	parId: [{ required: true, trigger: 'change' }],
	name: [{ required: true, trigger: 'blur' }],
	score: [{ required: true, trigger: 'blur' }],
};
export const useSearch = () => {
	const loading = ref(false);
	const page = ref({
		pageSize: 10,
		current: 1,
		total: 0,
	});
	const searchForm = ref({
		name: '',
	});
	const tableData = ref([]);
	const init = async () => {
		try {
			loading.value = true;
			let res = await getArticleCateList({ ...searchForm.value, ...page.value });
			loading.value = false;
			if (res.code !== 200) return;
			const { data, total } = res.data;
			tableData.value = data;
			page.value.total = total;
		} catch (err) {
			loading.value = false;
		}
	};
	onMounted(init);
	return {
		page,
		searchForm,
		tableData,
		loading,
		init,
	};
};
export const useAdd = (init) => {
	const isAdd = ref(false);
	const addDialogVisible = ref(false);
	const formRef = ref();
	const ruleForm = ref({});
	const saveLoading = ref(false);
	return {
		addDialogVisible,
		isAdd,
		saveLoading,
		formRef,
		ruleForm,
		title: computed(() => `${isAdd.value ? '新增' : '编辑'}分类`),
		toAdd() {
			addDialogVisible.value = true;
			isAdd.value = true;
			ruleForm.value = { showStatus: 1, score: 0 };
		},
		toEdit(row) {
			addDialogVisible.value = true;
			isAdd.value = false;
			ruleForm.value = deepCopy(row);
		},
		async toSave() {
			formRef.value.validate(async (valid) => {
				if (valid) {
					const request = isAdd.value ? addArticleCate : editArticleCate;
					saveLoading.value = true;
					let res = await request(ruleForm.value);
					saveLoading.value = false;
					if (res.code !== 200) return;
					ElMessage.success('保存成功！');
					addDialogVisible.value = false;
					init();
				}
			});
		},
		async changeStatus(cateItem) {
			let res = await editArticleCate(cateItem);
			if (res.code === 200) {
				ElMessage.success('更改状态成功！');
			} else {
				init();
			}
		},
	};
};
